package com.yt.app.api.action;

import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.google.common.base.Joiner;
import com.yt.app.api.action.base.BaseAction;
import com.yt.app.api.util.Config;
import com.yt.app.api.util.UploadImageUtils;
import com.yt.app.api.vo.BaseVo;
import com.yt.app.api.vo.UserReportVo;
import com.yt.app.api.vo.UserVo;
import com.yt.app.core.interfaces.UserReportService;
import com.yt.app.core.model.UserContact;
import com.yt.app.core.model.UserReport;
import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.util.MD5Util;
import com.yt.website.api.interfaces.UserInfoService;
import com.yt.website.api.model.UserInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@Api(tags = "12.报告管理")
@RequestMapping("/my/report")
public class UserReportController extends BaseAction{
    @Autowired
    private UserReportService userReportService;

    @ApiOperation(value="报告信息", httpMethod = "GET")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "报告信息", response = UserReport.class)})
    @RequestMapping("/get")
    public @ResponseBody  Object getReport(
            @ApiParam("ID") @RequestParam(name="id", required = true, defaultValue = "0") Long id,
            @ApiIgnore BaseVo vo,
            @ApiIgnore HttpServletRequest request){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        UserReport userReport = userReportService.get(id);
        if(userReport != null){
            fixPrivateFileUrl(userReport);
            msgBean.put("data", new UserReportVo(userReport));
        }

        return msgBean.returnMsg();
    }
    @ApiOperation(value="报告列表", httpMethod = "GET")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "报告", response = UserReportVo.class)})
    @RequestMapping("/list")
    public @ResponseBody  Object listProfile(
            @ApiParam("上一页最后一个ID") @RequestParam(name="lastId", required = true, defaultValue = "0") Long lastId,
            @ApiIgnore BaseVo vo,
            @ApiIgnore HttpServletRequest request){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        QueryFilter filter = new DynamicSQLFilterImpl();
        filter.addFilter("Q_uid_L_EQ", String.valueOf(uid));
        if(lastId >0){
            filter.addFilter("Q_id_L_GT", String.valueOf(lastId));
        }
        List<UserReport> reportList = userReportService.find(filter);
        if(reportList != null && !reportList.isEmpty()){
            lastId = reportList.get(reportList.size() -1).getId();
        }else{
            lastId = -1L;
        }
        List<UserReportVo> voList = new ArrayList<UserReportVo>();
        for(UserReport report : reportList){
            fixPrivateFileUrl(report);
            voList.add(new UserReportVo(report));
        }
        msgBean.put("lastId", lastId);
        msgBean.put("reports", voList);

        return msgBean.returnMsg();
    }
    @ApiOperation(value="删除报告", httpMethod = "POST")
    @RequestMapping("/delete")
    public @ResponseBody  Object delete(
            @ApiParam("ID") @RequestParam(name="id", required = true, defaultValue = "0") Long id,
            @ApiIgnore BaseVo vo,
            @ApiIgnore HttpServletRequest request){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        UserReport userReport = userReportService.get(id);
        if(!userReport.getUid().equals(uid)){
            return msgBean.failure("非法操作").returnMsg();
        }
        userReportService.remove(id);

        return msgBean.returnMsg();
    }

    @ApiOperation(value="保存信息（新增或修改）", httpMethod = "POST")
    @RequestMapping("/save")
    public @ResponseBody  Object updateProfile(
            @ApiParam("机构名称") @RequestParam(value = "institution") String institution,
            @ApiParam("文件列表，多个文件逗号分隔") @RequestParam(value = "files") String files,
            @ApiParam("报告日期") @RequestParam(value = "reportDate") Integer reportDate,
            @ApiParam("备注") @RequestParam(value = "comments", required = false, defaultValue = "") String comments,
            @ApiParam("ID") @RequestParam(value = "id", required = false) Long id,
            @ApiIgnore BaseVo vo,
            @ApiIgnore HttpServletRequest request){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        UserReport userReport = userReportService.get(uid);
        //过滤签名参数
        String[] file = files.split(",");
        List<String> fileList = new ArrayList<String>();
        for(String f : file){
            fileList.add(f.split("\\?")[0]);
        }
        files = Joiner.on(",").join(fileList);
        if(userReport != null){
            userReport.setFiles(files);
            userReport.setInstitution(institution);
            userReport.setReportDate(reportDate);
            userReport.setComments(comments);
            userReport.setUploadDate(System.currentTimeMillis()/1000);
            userReportService.update(userReport);
        }else{
            userReport = new UserReport();
            userReport.setUid(uid);
            userReport.setFiles(files);
            userReport.setInstitution(institution);
            userReport.setReportDate(reportDate);
            userReport.setComments(comments);
            userReport.setUploadDate(System.currentTimeMillis()/1000);
            userReportService.insert(userReport);

        }

        return msgBean.returnMsg();
    }

    @ApiOperation(value="上传报告文件", httpMethod = "POST")
    @RequestMapping("/uploadReport")
    public @ResponseBody  Object uploadReport(
            @ApiIgnore HttpServletRequest request
    ){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        List<String> urlList = new ArrayList<String>();
        List<MultipartFile> files = getMultipartFileList(request);
        for(MultipartFile file : files) {
            String uri = UploadImageUtils.uploadImage(file, "report", false);
            urlList.add(UploadImageUtils.getPrivateUrl(uri, 60 * 60));
        }

        msgBean.put("urls", Joiner.on(",").join(urlList));
        return msgBean.returnMsg();
    }

    private void fixPrivateFileUrl(UserReport report){
        String urls = report.getFiles();
        String url[] = urls.split(",");
        List<String> urlList = new ArrayList<String>();
        for(String u : url){
            urlList.add(UploadImageUtils.getPrivateUrl(u, 60 * 60));
        }
        report.setFiles(Joiner.on(",").join(urlList));
    }

    private List<MultipartFile> getMultipartFileList(HttpServletRequest request){
        List<MultipartFile> files = new ArrayList<MultipartFile>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (request instanceof MultipartHttpServletRequest) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator iter = multiRequest.getFileNames();
            if (multipartResolver.isMultipart(request) && iter.hasNext()) {
                while (iter.hasNext()) {
                    List<MultipartFile> fileRows = multiRequest
                            .getFiles(iter.next().toString());
                    if (fileRows != null && fileRows.size() != 0) {
                        for (MultipartFile file : fileRows) {
                            if (file != null && !file.isEmpty()) {
                                files.add(file);
                            }
                        }
                    }
                }
            }
        }
        return files;
    }
}
